// AudioPlay.cpp : �������̨Ӧ�ó������ڵ㡣
//

#include<math.h>
#include<string>
#include "SignalResample.h"

using namespace std;
//*************************************************
//                   ���
//*************************************************
int GetAudioDataByIQ(short DemoMode, double* IData, double* QData, int Len, double* AudioData)
{
	/*double mPreI = IData[0]; 
	double mPreQ = QData[0];*/
	double mPreI = 0;
	double mPreQ = 0;
	double dfI;
	double dfQ;
	double tmpV2;

	int res = 0;
	int a = 0, b = 0;
	double tmpV = 0;
	for (int i = 0; i < Len; i++)
	{
		dfI = IData[i];
		dfQ = QData[i];
		switch (DemoMode)
		{

		case 0://FM
			tmpV = (dfI * dfI + dfQ * dfQ);
			if (tmpV == 0)
			{
				AudioData[i] = 0;
			}
			else
			{
				tmpV2 = (mPreI * dfQ - dfI * mPreQ) / tmpV;
				if (tmpV2 > 1 || tmpV2 < -1)
				{
					if (i == 0)
					{
						AudioData[i] = 0;
					}
					else
						AudioData[i] = AudioData[i - 1];
				}
				else
					AudioData[i] =  tmpV2;
			}
			mPreI = dfI;
			mPreQ = dfQ;
			break;
		case 1://AM
			AudioData[i] = sqrt(dfI * dfI + dfQ * dfQ);
			res++;
			break;
		case 2://CW
			AudioData[i] = dfI;
			break;
		case 3://SSB
			AudioData[i] = sqrt(dfI * dfI + dfQ * dfQ);
			//AudioData[i] = dfI;
			break;
		default:
			break;
		}
	}
	return res;
}
//*************************************************
//     �ⲿ���û�ȡ�ز����������
//*************************************************
void GetAudioData(short DemoMode, double* IData, double* QData, int Len, double ChBw,
	bool *errFlag, int* AudioDataLen, double* AudioData)
{
	//�������ܣ���Ƶ�źŽ��
	//���룺
	//     short DemoMode, ������ͣ�0->FM��1->AM��2->CW��3->SSB��
	//     double* IData, I·���ݣ�һά���飬����ΪLen��
	//     double* QData, Q·���ݣ�һά���飬����ΪLen��
	//     int Len, I/Q���ݳ��ȣ�
	//     double ChBw, ��Ƶ��������λHz
	//�����
	//     bool *errFlag, �����־��������errFlag=trueʱ���ڴ���errFlag=falseʱAudioData��Ч��
	//     int* AudioDataLen, ��Ƶ�������ĳ��ȣ�
	//     double* AudioData����Ƶ��������һά���飬����ΪAudioDataLen��
	//============1�����==================//
	double* _tempAudioData = new double[Len];
	GetAudioDataByIQ(DemoMode, IData, QData, Len, _tempAudioData);
	//==========2���ز���==========//
	double lBandWide = ChBw;
	int lbwfs = int(lBandWide * 1.25);
	//int lbwfs = 200000; 
	//int fs = 44100; //������15kHz��Ӧ�Ĳ�����:22050Hz,44100Hz,48000 
	//int fs = 22050; 
    int fs = 20000; 
	//int fs = 14000; 
	
	vector<double> inputQ(Len), outputQ(Len);
	inputQ.assign(_tempAudioData, _tempAudioData + Len);
	SignalResample(fs, lbwfs, inputQ, errFlag, outputQ);
	
	*AudioDataLen = (int)outputQ.size();
	for (int i = 0; i < *AudioDataLen; i++)
	{
		AudioData[i] = outputQ[i];
	}
	delete[](_tempAudioData); _tempAudioData = NULL;
}

